package util

import (
	"github.com/json-iterator/go"
	"os"
	"os/user"
	"runtime"
	"path/filepath"
	"time"
)

func StringifyJson(obj interface{}) string {
	result, _ := jsoniter.MarshalToString(obj)
	return result
}

func ParseJson(str string, result interface{}) error {
	return jsoniter.UnmarshalFromString(str, result)
}

func StringifyJsonToBytes(obj interface{}) []byte {
	result, _ := jsoniter.Marshal(obj)
	return result
}

func ParseJsonFromBytes(data []byte, result interface{}) error {
	return jsoniter.Unmarshal(data, result)
}

func HomeDir() string {
	home := os.Getenv("HOME")
	if home == "" {
		if curU, err := user.Current(); err == nil {
			home = curU.HomeDir
		}
	}
	if home == "" {
		panic("can't get home dir")
	}
	return home
}

func AppDataDir(appName string) string {
	if appName == "" {
		panic("app name can't be empty")
	}
	home := HomeDir()
	if runtime.GOOS == "windows" {
		return filepath.Join(home, "AppData", appName)
	} else {
		return filepath.Join(home, appName)
	}
}

func StopChanClosed(stop chan struct{}) bool {
	if stop == nil {
		return true
	}
	select {
	case _, ok := <- stop:
		return !ok
	case <- time.After(100 * time.Microsecond):
		return false
	}
}